package se.sigma.selenium.testing;

import java.io.File;
import java.io.IOException;
// import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public abstract class SeleniumTest {

    protected WebDriver driver;
    protected boolean acceptNextAlert = true;
    
    private final static int SLEEP  = 750;

    public SeleniumTest(WebDriver newDriver) {
        this.driver = newDriver;
    }

    protected String closeAlertAndGetItsText() {
        try {
            Alert alert = driver.switchTo().alert();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alert.getText();
        } finally {
            acceptNextAlert = true;
        }
    }

    protected void log(String text) {
        System.out.println(text);
    }

    protected boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

    protected void refresh() {
        log("Refresh browser");
        driver.navigate().refresh();
    }

    protected void takeScreenShot(RuntimeException e, String fileName) {
/*        File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File(fileName + ".png"));
        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
        throw e; */
    }
    
    private void waitForElementPresent(By by, int timeout, boolean toggle) throws Exception {
        
        for (int i = 0; i < timeout; i++) {
            try {
                if(toggle) {
                    // This is when want to find the element
                    driver.findElement(by);
                    break;
                } else {
                    // This is when we want to wait for element to disappear
                    if(!isElementPresent(by)) break;
                }
            } catch (NoSuchElementException e) {
                
            } finally {
                Thread.sleep(SLEEP);
            }
        }
    }
    
    protected void waitForElementPresent(By by, int timeout) throws Exception {
        waitForElementPresent(by, timeout, true);
    }
    
    protected void waitForElementNotPresent(By by, int timeout) throws Exception {
        waitForElementPresent(by, timeout, false);
    }
}